﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Web;
using System.IO;
using System.Web.Caching;
using System.Collections.Specialized;

namespace XUtility
{
    /// <summary>
    /// Web 工具类
    /// </summary>
    public abstract class WebClass
    {
        #region 输出硬盘文件，提供下载 支持大文件、续传、速度限制、资源占用小
        ///<summary>
        /// 输出硬盘文件，提供下载 支持大文件、续传、速度限制、资源占用小
        /// </summary>
        /// <param name="_Request">Page.Request对象</param>
        /// <param name="_Response">Page.Response对象</param>
        /// <param name="_fileName">下载文件名</param>
        /// <param name="_fullPath">带文件名下载路径</param>
        /// <param name="_speed">每秒允许下载的字节数</param>
        /// 返回是否成功
        public static Boolean ResponseFile(HttpRequest _Request, HttpResponse _Response, String _fileName, String _fullPath, Int64 _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    Int64 fileLength = myFile.Length;
                    Int64 startBytes = 0;

                    Int32 pack = 10240; //10K bytes
                    //Int32 sleep = 200;   //每秒5次   即5*10K bytes每秒
                    Int32 sleep = (int)Math.Floor(1000.0 * pack / _speed) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        String[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    Int32 maxCount = (int)Math.Floor(1.0 * (fileLength - startBytes) / pack) + 1;

                    for (Int32 i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            System.Threading.Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                    //_Response.Flush();
                    //_Response.End();
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 下载文件 1:虚拟路径 2:绝对路径
        /// <summary>
        /// 下载文件 1:虚拟路径 2:绝对路径
        /// </summary>
        /// <param name="path">路径</param>
        ///<param name="type">1:虚拟路径 2:绝对路径</param>
        public static void Downloads(String path, Int32 type)
        {
            FileInfo DownloadFile;
            if (type == 1)
            {
                DownloadFile = new FileInfo(MapPaths(path)); //设置要下载的文件,虚拟路径
            }
            else
            {
                DownloadFile = new FileInfo(path); //设置要下载的文件,绝对路径
            }
            HttpContext.Current.Response.Clear();                            //清除缓冲区流中的所有内容输出
            HttpContext.Current.Response.ClearHeaders();                     //清除缓冲区流中的所有头
            HttpContext.Current.Response.Buffer = false;                     //设置缓冲输出为false
            //设置输出流的 HTTP MIME 类型为application/octet-stream
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            //将 HTTP 头添加到输出流
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            //将指定的文件直接写入 HTTP 内容输出流。
            HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
            HttpContext.Current.Response.Flush();       //向客户端发送当前所有缓冲的输出
            HttpContext.Current.Response.End();         //将当前所有缓冲的输出发送到客户端
        }
        #endregion

        #region 无法用Server对文件进行转换路径的时候
        /// <summary>
        /// 获得文件物理路径
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public static String MapPaths(String strPath)
        {
            if (System.Web.HttpContext.Current != null)
            {
                return System.Web.HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用   
            {
                //strPath = strPath.Replace("/", "");
                //strPath = strPath.Replace("~", "");
                //if (strPath.StartsWith("\\"))
                //{
                //    strPath = strPath.TrimStart('\\');
                //}
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        /// <summary>
        /// 编码文本
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String UrlEncode(String str)
        {
            if (System.Web.HttpContext.Current != null)
            {
                return System.Web.HttpContext.Current.Server.UrlEncode(str);
            }
            else
            {
                return HttpUtility.UrlEncode(str);
            }
        }

        /// <summary>
        /// 解码文本
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static String UrlDecode(String str)
        {
            if (System.Web.HttpContext.Current != null)
            {
                return System.Web.HttpContext.Current.Server.UrlDecode(str);
            }
            else
            {
                return HttpUtility.UrlDecode(str);
            }
        }
        #endregion

        #region 取得网站的根目录
        /// <summary>
        /// 取得网站的根目录的URL,包括虚拟目录
        /// </summary>
        /// <returns>如：https：//www.湛江金蝶.com/apppath </returns>
        public static String GetRootURI()
        {
            String AppPath = "";
            HttpContext HttpCurrent = HttpContext.Current;
            HttpRequest Req;
            if (HttpCurrent != null)
            {
                Req = HttpCurrent.Request;

                String UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
                if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
                    //直接安装在   Web   站点   
                    AppPath = UrlAuthority;
                else
                    //安装在虚拟子目录下   
                    AppPath = UrlAuthority + Req.ApplicationPath;
            }

            return AppPath + "/";
        }
        #endregion

        #region 用户状态保存名称
        /// <summary>
        /// 用户状态保存名称
        /// </summary>
        public const String StateName = "loginuser";
        #endregion

        #region 简单获取客户端IP
        /// <summary>
        /// 简单获取客户端IP
        /// </summary>
        /// <returns></returns>
        public static String GetClientIP()
        {
            String result = HttpContext.Current.Request.UserHostAddress;

            //方法2      
            //string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //if (null == result ||result == String.Empty) 
            //{ 
            //    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            //} 
            //if (null == result ||result == String.Empty) 
            //{ 
            //    result = HttpContext.Current.Request.UserHostAddress; 
            //} 
            return result;
        }
        #endregion

        #region 取得客户端真实IP。如果有代理则取第一个非内网地址
        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理 
                if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式 
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。 
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];    //找到不是内网的地址 
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式 
                        return result;
                    else
                        result = null;    //代理中的内容 非IP，取IP 
                }

            }

            string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty)
                ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;

            return result;

        }
        #endregion

        #region 判断是否是IP地址格式 0.0.0.0
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        private static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15)
                return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        #endregion

        #region ARP 操作
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);
        #endregion

        #region 获得用户MAC地址
        /// <summary>
        /// 获得用户MAC地址
        /// </summary>
        /// <returns></returns>
        public static String GetMAC()
        {
            string IP = GetIP();
            try
            {
                string userip = IP;
                string strClientIP = IP;
                Int32 ldest = inet_addr(strClientIP); //目的地的ip 
                Int32 lhost = inet_addr("");   //本地服务器的ip 
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                //if (mac_src == "0")
                //{
                //    if (userip == "127.0.0.1")
                //        Response.Write("正在访问Localhost!");
                //    else
                //        Response.Write("欢迎来自IP为" + userip + "的朋友！" + "");
                //    return;
                //}
                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, "0");
                }
                string mac_dest = "";
                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
                return mac_dest;
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 获得远程客户端主机名
        /// <summary>
        /// 获得远程客户端主机名
        /// </summary>
        /// <returns></returns>
        public static String GetPCName()
        {
            string pcName = "";
            try
            {
                pcName = System.Net.Dns.GetHostEntry(GetIP()).HostName;
                //pcName = HttpContext.Current.Request.ServerVariables["REMOTE_HOST"];
            }
            catch
            {

            }
            return pcName;
        }
        #endregion

        #region 获得网址的参数
        #region 获取 String 类型参数
        /// <summary>
        /// 获取 String 类型参数
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static String RequestString(String sParam, String defaultValue = "")
        {
            var str = HttpContext.Current.Request.Form[sParam];
            //if (str == null)
            //    str = HttpContext.Current.Request[sParam] == null ? defaultValue : HttpContext.Current.Request[sParam].ToString().Trim();

            if (String.IsNullOrEmpty(str))
                str = HttpContext.Current.Request[sParam];
            if (String.IsNullOrEmpty(str) && defaultValue != "")
                str = defaultValue;
            if (str == null) str = String.Empty;
            if (!String.IsNullOrEmpty(str)) str = str.Trim();
            return str;
        }
        #endregion

        #region Int32 类型参数
        /// <summary>
        /// 获取 Int32 类型参数
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static Int32 RequestInt(String sParam, Int32 defaultValue = 0)
        {
            Int32 iValue;
            String sValue = RequestString(sParam);

            if (!Int32.TryParse(sValue, out iValue))
                return defaultValue;
            return iValue;
        }
        /// <summary>
        /// 获取 可空Int32 类型参数
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static Int32? RequestInt(String sParam, Int32? defaultValue)
        {
            Int32 iValue;
            String sValue = RequestString(sParam);

            if (String.IsNullOrWhiteSpace(sValue))
                return defaultValue;
            else
            {
                if (!Int32.TryParse(sValue, out iValue))
                    return defaultValue;
            }
            return iValue;
        }
        #endregion

        #region DateTime 类型参数
        /// <summary>
        /// 获取 DateTime 类型参数
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <returns></returns>
        public static DateTime RequestDateTime(String sParam)
        {
            return RequestDateTime(sParam, DateTime.Now).Value;
        }
        /// <summary>
        /// 获取 可空DateTime 类型参数
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static DateTime? RequestDateTime(String sParam, DateTime? defaultValue)
        {
            DateTime dValue;
            String sValue = RequestString(sParam);

            if (String.IsNullOrWhiteSpace(sValue) || !DateTime.TryParse(sValue, out dValue) || (dValue.Year == 0001))
            {
                if (defaultValue.HasValue)
                {
                    if (sParam.StartsWith("date"))
                    {
                        defaultValue = defaultValue.Value.Date;
                    }
                    else if (sParam.StartsWith("datt"))
                    {
                        defaultValue = defaultValue.Value;
                    }
                }
                return defaultValue;
            }
            return dValue;
        }
        #endregion

        #region Boolean 类型参数
        /// <summary>
        /// 把请求参数转换为Boolean类型
        /// <para>注释：</para>
        /// <para>  这个方法主要用于获取checkbox控件的值</para>
        /// <para>   true:[非空]  false:[null | "" | "off" | "0"]</para>
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <returns>参数值</returns>
        public static Boolean RequestBoolean(String sParam)
        {
            Boolean bValue = true;
            String sValue = RequestString(sParam);

            if (String.IsNullOrWhiteSpace(sValue) || ("false".Equals(sValue, StringComparison.OrdinalIgnoreCase)) || ("off".Equals(sValue, StringComparison.OrdinalIgnoreCase)) || ("0".Equals(sValue)) || "undefined".Equals(sValue, StringComparison.OrdinalIgnoreCase))
                bValue = false;
            return bValue;
        }
        /// <summary>
        /// 把请求参数转换为Boolean类型
        /// <para>注释：</para>
        /// <para>  这个方法主要用于获取checkbox控件的值</para>
        /// <para>   true:[非空]  false:[null | "" | "off" | "0"]</para>
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>参数值</returns>
        public static Boolean RequestBoolean(String sParam, Boolean defaultValue)
        {
            Boolean bValue;
            String sValue = RequestString(sParam);

            if (!Boolean.TryParse(sValue, out bValue))
            {
                Int32 i;
                if (Int32.TryParse(sValue, out i))
                    bValue = i.ToBoolean();
                else
                    return defaultValue;
            }

            return bValue;
        }
        /// <summary>
        /// 把请求参数转换为 [可空Boolean] 类型 
        /// <para>注释：</para>
        /// <para>  这个方法主要用于获取checkbox控件的值</para>
        /// <para>   true:[非空]  false:[null | "" | "off" | "0"]</para>
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>参数值</returns>
        public static Boolean? RequestBoolean(String sParam, Boolean? defaultValue)
        {
            Boolean iValue;
            String sValue = RequestString(sParam);

            if (!Boolean.TryParse(sValue, out iValue))
                return defaultValue;

            return iValue;
        }
        #endregion

        #region File 类型参数 [上传控件]
        /// <summary>
        /// 获取 File 类型参数 [上传控件]
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <returns></returns>
        public static HttpPostedFile RequestFile(String sParam)
        {
            return HttpContext.Current.Request.Files[sParam];
        }
        #endregion

        #region Decimal 类型参数

        /// <summary>
        /// 把请求参数转换为Decimal类型
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue"></param>
        /// <returns>参数值</returns>
        public static Decimal RequestDecimal(String sParam, Decimal defaultValue = 0)
        {
            Decimal iValue;
            String sValue = RequestString(sParam);

            if (String.IsNullOrWhiteSpace(sValue))
                return defaultValue;
            else
            {
                if (!Decimal.TryParse(sValue, out iValue))
                    return defaultValue;
            }

            return iValue;
        }
        #endregion

        #region Double 类型参数
        /// <summary>
        /// 把请求参数转换为 Double 类型
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <returns>参数值</returns>
        public static Double RequestDouble(String sParam)
        {
            Double dValue = 0D;
            String sValue = RequestString(sParam);

            if (sValue.HasValue())
            {
                Double.TryParse(sValue, out dValue);
            }

            return dValue;
        }
        /// <summary>
        /// 把请求参数转换为 Double 类型
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <param name="defaultValue"></param>
        /// <returns>参数值</returns>
        public static Double? RequestDouble(String sParam, Double? defaultValue)
        {
            Double iValue;
            String sValue = RequestString(sParam);

            if (String.IsNullOrWhiteSpace(sValue))
                return defaultValue;
            else
            {
                if (!Double.TryParse(sValue, out iValue))
                    return defaultValue;
            }

            return iValue;
        }
        /// <summary>
        /// 把请求参数转换为 Double 类型
        /// </summary>
        /// <param name="sParam">参数名称</param>
        /// <returns>参数值</returns>
        public static Double RequestPerCent(String sParam)
        {
            return RequestDouble(sParam) / 100;
        }
        #endregion
        #endregion

        #region 获得CPU点
        ///// <summary>
        ///// 获得CPU点
        ///// </summary>
        ///// <returns></returns>
        //public static string GetCPU()
        //{
        //    string strCpu = null;
        //    ManagementClass myCpu = new ManagementClass("win32_Processor");
        //    ManagementObjectCollection myCpuConnection = myCpu.GetInstances();
        //    foreach(ManagementObject myObject in myCpuConnection)
        //    {
        //        strCpu = myObject.Properties["Processorid"].Value.ToString();
        //        break;
        //    }
        //    return strCpu;
        //}
        #endregion

        #region 取得设备硬盘的卷标号
        ///// <summary>
        ///// 取得设备硬盘的卷标号 
        ///// </summary>
        ///// <returns></returns>
        //public static string GetDiskVolumeSerialNumber()
        //{
        //    ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        //    ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
        //    disk.Get();
        //    return disk.GetPropertyValue("VolumeSerialNumber").ToString();
        //}
        #endregion

        #region 获取标准时间，优先网络时间，没有就本地时间
        /// <summary>
        /// 获取标准时间，优先网络时间，没有就本地时间
        /// </summary>
        /// <returns></returns>
        public static DateTime DataStandardTime()
        {//返回国际标准时间
            //只使用的arrTimeServer的IP地址，未使用域名
            String[,] arrTimeServer = new String[14, 2];
            Int32[] arrSort = new Int32[] { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 };
            arrTimeServer[0, 0] = "time-a.nist.gov";
            arrTimeServer[0, 1] = "129.6.15.28";
            arrTimeServer[1, 0] = "time-b.nist.gov";
            arrTimeServer[1, 1] = "129.6.15.29";
            arrTimeServer[2, 0] = "time-a.timefreq.bldrdoc.gov";
            arrTimeServer[2, 1] = "132.163.4.101";
            arrTimeServer[3, 0] = "time-b.timefreq.bldrdoc.gov";
            arrTimeServer[3, 1] = "132.163.4.102";
            arrTimeServer[4, 0] = "time-c.timefreq.bldrdoc.gov";
            arrTimeServer[4, 1] = "132.163.4.103";
            arrTimeServer[5, 0] = "utcnist.colorado.edu";
            arrTimeServer[5, 1] = "128.138.140.44";
            arrTimeServer[6, 0] = "time.nist.gov";
            arrTimeServer[6, 1] = "192.43.244.18";
            arrTimeServer[7, 0] = "time-nw.nist.gov";
            arrTimeServer[7, 1] = "131.107.1.10";
            arrTimeServer[8, 0] = "nist1.symmetricom.com";
            arrTimeServer[8, 1] = "69.25.96.13";
            arrTimeServer[9, 0] = "nist1-dc.glassey.com";
            arrTimeServer[9, 1] = "216.200.93.8";
            arrTimeServer[10, 0] = "nist1-ny.glassey.com";
            arrTimeServer[10, 1] = "208.184.49.9";
            arrTimeServer[11, 0] = "nist1-sj.glassey.com";
            arrTimeServer[11, 1] = "207.126.98.204";
            arrTimeServer[12, 0] = "nist1.aol-ca.truetime.com";
            arrTimeServer[12, 1] = "207.200.81.113";
            arrTimeServer[13, 0] = "nist1.aol-va.truetime.com";
            arrTimeServer[13, 1] = "64.236.96.53";
            Int32 portNum = 13;
            String hostName;
            Byte[] bytes = new Byte[1024];
            Int32 bytesRead = 0;
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            for (Int32 i = 0; i < 13; i++)
            {
                hostName = arrTimeServer[arrSort[i], 1];
                try
                {
                    client.Connect(hostName, portNum);
                    System.Net.Sockets.NetworkStream ns = client.GetStream();
                    bytesRead = ns.Read(bytes, 0, bytes.Length);
                    client.Close();
                    break;
                }
                catch
                {
                    bytesRead = 0;
                }
            }
            Char[] sp = new Char[1];
            sp[0] = ' ';
            System.DateTime dt = new DateTime();

            try
            {
                if (0 == bytesRead)
                    dt = DateTime.Now;
                else
                {
                    String str1;
                    str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead);

                    String[] s;
                    s = str1.Split(sp);
                    dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间
                    dt = dt.AddHours(8);//得到北京时间*/
                }
            }
            catch
            {
                dt = DateTime.Now;
            }

            return dt;
        }
        #endregion

        #region Cookie操作
        /// <summary>
        /// 获得单值Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static String GetCookie(String key)
        {
            var c = HttpContext.Current.Request.Cookies[key];
            if (c == null) return "";

            return c.Value;
        }

        /// <summary>
        /// 获得多值Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static NameValueCollection GetCookies(String key)
        {
            var c = HttpContext.Current.Request.Cookies[key];
            if (c == null) return null;

            return c.Values;
        }

        /// <summary>
        /// 设置单个Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="datavalue">值</param>
        /// <param name="over_time">过期日期，默认1小时</param>
        /// <returns></returns>
        public static Boolean SetCookie(String key, String datavalue, DateTime? over_time = null)
        {
            try
            {
                var acookie = new HttpCookie(key);
                acookie.Value = datavalue;
                acookie.Expires = over_time ?? DateTime.Now.AddHours(1); // 默认保存1小时
                HttpContext.Current.Response.Cookies.Add(acookie);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 设置多个Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="datavalue">值</param>
        /// <param name="over_time">过期日期，默认1小时</param>
        /// <returns></returns>
        public static Boolean SetCookies(String key, NameValueCollection datavalue, DateTime? over_time = null)
        {
            try
            {
                var acookie = new HttpCookie(key);
                foreach (var d in datavalue.AllKeys)
                {
                    acookie.Values[d] = datavalue[d];
                }

                acookie.Expires = over_time ?? DateTime.Now.AddHours(1); // 默认保存1小时
                HttpContext.Current.Response.Cookies.Add(acookie);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion
    }
}
